package com.jcommander.gui.table;

import java.awt.Component;
import java.awt.Font;

import javax.swing.Icon;
import javax.swing.JLabel;
import javax.swing.JTable;
import javax.swing.table.TableCellRenderer;

import com.jcommander.model.IconLabel;

public class IconLabelRenderer extends JLabel implements TableCellRenderer {
	
	private static final long serialVersionUID = -267857991826052340L;
	private Font uhOhFont;
	
 	public IconLabelRenderer() {
        setOpaque(true); 
    }

    public Component getTableCellRendererComponent(
                            JTable table, Object value,
                            boolean isSelected, boolean hasFocus,
                            int row, int column) {
    	if (isSelected) {
            setBackground(table.getSelectionBackground());
            setForeground(table.getSelectionForeground());
        } else {
            setBackground(table.getBackground());
            setForeground(table.getForeground());
        }
 
    	IconLabel item = (IconLabel)value;
        
    	//Set the icon and text.  If icon was null, say so.
        Icon icon = (item != null) ? item.getIcon() : null;
        String label = (item != null) ? item.getLabel() : null;
        setIcon(icon);
        if (icon != null) {
            setText(label);
            setFont(table.getFont());
        } else {
            setUhOhText(label + " (no image available)",table.getFont());
        }

        return this;
    }
    

    //Set the font and text when no image was found.
    protected void setUhOhText(String uhOhText, Font normalFont) {
        if (uhOhFont == null) { //lazily create this font
            uhOhFont = normalFont.deriveFont(Font.ITALIC);
        }
        setFont(uhOhFont);
        setText(uhOhText);
    }
}
